package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.Location;
import com.rockcent.mall.lib.domain.MerchantStore;
import com.rockcent.mall.lib.domain.enumclass.MerchantStoreStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantStoreType;
import com.rockcent.mall.lib.dto.LocationDto;
import com.rockcent.mall.lib.dto.MerchantStoreCustomerDto;
import com.rockcent.mall.lib.dto.MerchantStoreDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.LocationHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangjh on 2016/9/27.
 */
@RestController
public class MerchantStoreController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MarketMerchantController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MerchantStoreRepository merchantStoreRepository;
    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private LocationHelper locationHelper;


    /**
     * @api {get} /merchant/store/list 商家门店列表
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccess {Long} id 门店ID
     * @apiSuccess {String} name 门店名称
     * @apiSuccess {String} number 门店编号
     * @apiSuccess {String} third 门店网址
     * @apiSuccess {String} locationStr 门店地址
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "id": 5,
     * "name": 大口九(客村店),
     * "number": 005,
     * "third": "http://www.baidu.com",
     * "address": "广州海珠客村地铁站是你家"
     * }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_STORE_LIST, method = RequestMethod.GET)
    public JsonResult merchantStoreList(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<MerchantStoreDto> merchantStoreList = merchantStoreRepository.findMerchantStoresList(userInfoDto.merchant.getId(), Whether.YES, MerchantStoreStatus.ENABLE, Whether.NO);
            merchantStoreList.forEach(merchantStoreDto -> {
                if(MerchantStoreType.valueOf(merchantStoreDto.getType())==MerchantStoreType.STORE&& merchantStoreDto.getLocationId()!=null) {
                    LocationDto locationDto = locationHelper.getFullLocation(merchantStoreDto.getLocationId());
                    merchantStoreDto.setLocationStr(locationDto.getProviceName() + locationDto.getCityName() + locationDto.getLocationName()+merchantStoreDto.getAddress());
                }
            });
            jsonResult.data = merchantStoreList;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/store/page 商家门店 分页
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} name 门店名称/编号
     * @apiParam {String} status <code>可选参数 ENABLE("启用"),DISABLE("停用") 不传代表全部</code> 门店状态
     * @apiParam {String} locationId <code>可选参数 不传代表全部</code> 省份、城市
     * @apiParam {String} type <code>可选参数 STORE("实体店"), SHOP("网店"); 不传代表全部类型</code> 店铺类型
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} merchantId <code>必选参数</code> 商户ID
     * @apiSuccess {Long} id 门店ID
     * @apiSuccess {String} name 门店名称
     * @apiSuccess {String} number 门店编号
     * @apiSuccess {String} third 门店网址
     * @apiSuccess {String} locationStr 门店地址
     * @apiSuccessExample {json} Success-Response:
     *{
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *  "data": [
     *      {
     *          "id": 5,
     *          "name": "asdasd",
     *          "third": "www.rockcent.com",
     *          "phone": "13533409812",
     *          "status": "ENABLE",
     *          "number": "001"
     *       }
     *   ],
     *   "totalCount": 1,
     *   "totalPage": 1,
     *   "pageNo": 0,
     *   "pageSize": 10,
     *   "url": "/merchant/store/page",
     *   "prevUrl": "/merchant/store/page?pageNo=0&pageSize=10",
     *   "nextUrl": "/merchant/store/page?pageNo=0&pageSize=10"
     *}
     *}
     */
    @RequestMapping(value = Routes.MERCHANT_STORE_PAGE, method = RequestMethod.GET)
    public JsonResult merchantStorePage(MerchantStoreDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<Long> locations = null;
            if (dto.getMerchantId() ==null) {
                jsonResult.remind("商户ID为空", log);
                return;
            }
            if (dto.getLocationId() != null) {
                locations = getLocationsByLocationId(dto.getLocationId(), dto);
            }
            PageResult pageResult = getPage(dto.getPageNo(), dto.getPageSize());
            if (StringUtils.isNotBlank(dto.getStatus())) {
                if (!EnumUtils.isValidEnum(MerchantStoreStatus.class, dto.getStatus())) {
                    jsonResult.remind("status 参数错误，必须为 ENABLE(\"启用\"), DISABLE(\"停用\")", log);
                    return;
                }
            }
            if (StringUtils.isNotBlank(dto.getType())) {
                if (!EnumUtils.isValidEnum(MerchantStoreType.class, dto.getType())) {
                    jsonResult.remind("type 参数错误，必须为 STORE(\"实体店\"), SHOP(\"网店\")", log);
                    return;
                }
            }

            PageResult<MerchantStoreDto> merchantStoreList = merchantStoreRepository.
                    findByMerchantIdPage(dto.getMerchantId(), userInfoDto.mall.getId(), Whether.YES, dto.getStatus(), dto.getType(), Whether.NO, dto.getName(), locations, pageResult);

            merchantStoreList.data.forEach(merchantStoreDto -> {
                if(MerchantStoreType.valueOf(merchantStoreDto.getType())==MerchantStoreType.STORE&& merchantStoreDto.getLocationId()!=null) {
                    LocationDto locationDto = locationHelper.getFullLocation(merchantStoreDto.getLocationId());
                    merchantStoreDto.setLocationStr(locationDto.getProviceName() + locationDto.getCityName() + locationDto.getLocationName()+merchantStoreDto.getAddress());
                }
            });

            merchantStoreList.setUrl(Routes.MERCHANT_STORE_PAGE);
            jsonResult.data = merchantStoreList;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /merchant/store/number 商家门店编号
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": "005"
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_STORE_NUMBER, method = RequestMethod.GET)
    public JsonResult merchantStoreNumber(HttpServletRequest request) {
        RestDoing doing = jsonResult -> {
            UserInfoDto userInfoDto = userHelper.getSession(request);
            long number = merchantStoreRepository.countByMerchantIdAndStatus(userInfoDto.merchant.getId(), MerchantStoreStatus.ENABLE);
            String storeCode = String.format("%03d", number + 1);
            jsonResult.data = storeCode;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /merchant/store/save 商家门店保存
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=STORE("实体店"), SHOP("网店")} type <code>必须参数</code> 门店类型
     * @apiParam {String} name <code>必须参数</code> 门店名称
     * @apiParam {String} number <code>必须参数</code> 门店编号
     * @apiParam {String} phone <code>必须参数</code> 门店电话  格式(可以座机+手机;手机+手机): 13532423434,13623423434
     * @apiParam {Long} locationId <code>必须参数</code> 门店所在区域ID
     * @apiParam {String} locationStr <code>必要参数 保存省市区名称</code> 省市区名称
     * @apiParam {String} address <code>当时门店类型为实体店(STORE) 为必须参数</code> 实体店地址
     * @apiParam {String} introduction 门店介绍
     * @apiParam {String} third <code>当时门店类型网店(SHOP) 为必须参数</code> 网店网址
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_STORE_SAVE, method = RequestMethod.POST)
    public JsonResult merchantStoreSave(HttpServletRequest request, @RequestBody MerchantStoreDto merchantStoreDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (merchantStoreDto.getName() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_NAME_IS_NOT_NULL,log);
                return;
            }
            if (merchantStoreDto.getPhone() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_PHONE_IS_NOT_NULL,log);
                return;
            }
            if (MerchantStoreType.STORE == MerchantStoreType.valueOf(merchantStoreDto.getType()) && (merchantStoreDto.getAddress() == null || merchantStoreDto.getLocationId() == null)) {
                jsonResult.errorParam(MerchantStore.CHECK_ADDRESS_IS_NOT_NULL,log);
                return;
            }
            if (MerchantStoreType.SHOP == MerchantStoreType.valueOf(merchantStoreDto.getType()) && merchantStoreDto.getSite() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_SITE_IS_NOT_NULL,log);
                return;
            }

            MerchantStore merchantStore = new MerchantStore();
            merchantStore.setMerchantId(userInfoDto.merchant.getId());
            merchantStore.setMallId(userInfoDto.mall.getId());
            merchantStore.setAddress(merchantStoreDto.getAddress());
            merchantStore.setIntroduction(merchantStoreDto.getIntroduction());
            merchantStore.setLocationId(merchantStoreDto.getLocationId());
            merchantStore.setLocationStr(merchantStoreDto.getLocationStr());
            merchantStore.setName(merchantStoreDto.getName());
            merchantStore.setNumber(merchantStoreDto.getNumber());
            merchantStore.setSite(merchantStoreDto.getSite());
            merchantStore.setPhone(merchantStoreDto.getPhone());
            merchantStore.setType(MerchantStoreType.valueOf(merchantStoreDto.getType()));
            merchantStoreRepository.save(merchantStore);
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /merchant/store/info 商家门店 信息
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必须参数</code> 门店ID
     * @apiSuccessExample {json} Success-Response:
     * {
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *       "id": 5,"
     *       "name": "御风茶庄",
     *       "type": "STORE",
     *       "address": "广州市海珠区",
     *       "phone": "13826988189",
     *       "proviceId": 130000,
     *       "cityId": 130400,
     *       "locationId": 130404,
     *       "proviceName": "河北省",
     *       "cityName": "邯郸市",
     *       "locationName": "复兴区",
     *       "number": "001",
     *       "introduction": "just for test"
     *       }
     *}
     */
    @RequestMapping(value = Routes.MERCHANT_STORE_INFO, method = RequestMethod.GET)
    public JsonResult merchantStoreInfo(HttpServletRequest request, MerchantStoreDto merchantStoreDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (merchantStoreDto.getId() == null) {
                jsonResult.remind("ID 不能为空", log);
                return;
            }
            MerchantStoreDto dto = merchantStoreRepository.getMerchantStoreById(merchantStoreDto.getId());

            if (dto == null) {
                jsonResult.remind("加载门店信息出错", log);
                return;
            } else {
                if (MerchantStoreType.STORE == MerchantStoreType.valueOf(dto.getType())) {
                    if (dto.getLocationId() != null) {
                        Location loc = locationRepository.findOne(dto.getLocationId());
                        int level = loc.getLevel();
                        if (level == 3) {
                            Location city = locationRepository.findOne(new Long(loc.getParentId()));
                            Location provice = locationRepository.findOne(new Long(city.getParentId()));
                            dto.setCityId(city.getId());
                            dto.setCityName(city.getLocationName());
                            dto.setProviceId(provice.getId());
                            dto.setProviceName(provice.getLocationName());
                            dto.setLocationName(loc.getLocationName());


                        } else if (level == 2) {
                            Location provice = locationRepository.findOne(new Long(loc.getParentId()));
                            Location city = loc;
                            dto.setCityId(city.getId());
                            dto.setCityName(city.getLocationName());
                            dto.setProviceId(provice.getId());
                            dto.setProviceName(provice.getLocationName());
                        }
                    }

                }
            }
            jsonResult.data = dto;
        };

        return doing.go(request, log);
    }


    /**
     * @api {post} /merchant/store/update 商家门店更新
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=STORE("实体店"), SHOP("网店")} type <code>必须参数</code> 门店类型
     * @apiParam {Long} id <code>必须参数</code> 门店ID
     * @apiParam {String} name <code>必须参数</code> 门店名称
     * @apiParam {String} phone <code>必须参数</code> 门店电话  格式(可以座机+手机;手机+手机): 13532423434,13623423434
     * @apiParam {Long} locationId <code>必须参数</code> 门店所在区域ID
     * @apiParam {String} address <code>当时门店类型为实体店(STORE) 为必须参数</code> 实体店地址
     * @apiParam {String} introduction 门店介绍
     * @apiParam {String} third <code>当时门店类型网店(SHOP) 为必须参数</code> 网店网址
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_STORE_UPDATE, method = RequestMethod.POST)
    public JsonResult merchantStoreUpdate(HttpServletRequest request, @RequestBody MerchantStoreDto merchantStoreDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (merchantStoreDto.getId() == null) {
                jsonResult.remind("ID 不能为空", log);
                return;
            }
            if (merchantStoreDto.getName() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_NAME_IS_NOT_NULL,log);
                return;
            }
            if (merchantStoreDto.getPhone() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_PHONE_IS_NOT_NULL,log);
                return;
            }
            if (merchantStoreDto.getType() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }
            if (MerchantStoreType.STORE == MerchantStoreType.valueOf(merchantStoreDto.getType()) && merchantStoreDto.getAddress() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_ADDRESS_IS_NOT_NULL,log);
                return;
            }
            if (merchantStoreDto.getType() == null || MerchantStoreType.SHOP == MerchantStoreType.valueOf(merchantStoreDto.getType()) && merchantStoreDto.getSite() == null) {
                jsonResult.errorParam(MerchantStore.CHECK_SITE_IS_NOT_NULL,log);
                return;
            }
            MerchantStore merchantStore = merchantStoreRepository.findOne(merchantStoreDto.getId());
            merchantStore.setMallId(userInfoDto.mall.getId());
            merchantStore.setIntroduction(merchantStoreDto.getIntroduction());
            merchantStore.setName(merchantStoreDto.getName());
            merchantStore.setPhone(merchantStoreDto.getPhone());
            merchantStore.setType(MerchantStoreType.valueOf(merchantStoreDto.getType()));
            if (MerchantStoreType.SHOP == MerchantStoreType.valueOf(merchantStoreDto.getType())) {
                merchantStore.setSite(merchantStoreDto.getSite());
            }
            if (MerchantStoreType.STORE == MerchantStoreType.valueOf(merchantStoreDto.getType())) {
                merchantStore.setAddress(merchantStoreDto.getAddress());
                merchantStore.setLocationId(merchantStoreDto.getLocationId());
            }


            merchantStoreRepository.save(merchantStore);

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/store/status/update 商家门店 启用|停用
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必须参数</code> 门店ID
     * @apiParam {String= ENABLE("启用"), DISABLE("停用");}  status <code>必须参数</code> 状态
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_STORE_STATUS_UPDATE, method = RequestMethod.PUT)
    public JsonResult merchantStoreStatusUpdate(HttpServletRequest request, @RequestBody MerchantStoreDto merchantStoreDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (merchantStoreDto.getId() == null) {
                jsonResult.remind("ID 不能为空", log);
                return;
            }
            if (merchantStoreDto.getStatus() == null || !EnumUtils.isValidEnum(MerchantStoreStatus.class, merchantStoreDto.getStatus())) {
                jsonResult.remind("status 参数错误，必须为 ENABLE(\"启用\"), DISABLE(\"停用\")", log);
                return;
            }
            MerchantStore merchantStore = this.merchantStoreRepository.findOne(merchantStoreDto.getId());
            merchantStore.setStatus(MerchantStoreStatus.valueOf(merchantStoreDto.getStatus()));
            merchantStoreRepository.saveAndFlush(merchantStore);
        };
        return doing.go(request, log);
    }

    @Transactional
    @RequestMapping(value = Routes.MERCHANT_STORE_CUSTOMER_SAVE, method = RequestMethod.PUT)
    public JsonResult addMerchantStoreCustomer(HttpServletRequest request, @RequestBody MerchantStoreCustomerDto merchantStoreCustomerDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (merchantStoreCustomerDto.getId() == null) {
                jsonResult.remind("ID 不能为空", log);
                return;
            }

        };
        return doing.go(request, log);
    }

    public List<Long> getLocationsByLocationId(Long locationId, MerchantStoreDto merchantStoreDto) {
        List<Location> result = new ArrayList<>();

        if (locationId != null) {
            result = locationRepository.getByParentId(locationId.toString());
        }
        if (result != null && !result.isEmpty()) {
            result.forEach(location -> {
                merchantStoreDto.getLocationIds().add(location.getId());
                getLocationsByLocationId(location.getId(), merchantStoreDto);
            });
        } else {
            merchantStoreDto.getLocationIds().add(locationId);
        }
        return merchantStoreDto.getLocationIds();
    }


}
